/**
 * 
 */
package com.hk.Mgr.web.controller;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.department.OrganizationExcelRes;
import com.hk.Mgr.web.message.department.OrganizationReq;
import com.hk.Mgr.web.message.department.OrganizationRes;
import com.hk.base.BaseCtrl;
import com.hk.base.Response;
import com.hk.base.ResponseBase;
import com.hk.commons.*;
import com.hk.commons.entity.Organization;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.vo.CheckInfo;
import com.hk.service.IOrganization;
import com.hk.service.IOrganization_New;
import com.hk.service.sys.ISysUser;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @author psx 组织架构实现类
 */
@Controller
@RequestMapping(value = BaseCtrl.MgrRootPath + "/OrganizationCtrl")
public class OrganizationCtrl extends BaseCtrl {

	@Autowired
	private ISysUser userService;

	@Autowired
	private IOrganization organizationService;

	@Autowired
	private IOrganization_New orgNewService;

	/**
	 * @Title: getOrganizationById
	 * @Description: 根据id获取系统模块信息
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/getById", method = RequestMethod.POST)
	public ResponseBase<Organization> getOrganizationById(
			@RequestBody OrganizationReq req) {
		ResponseBase<Organization> resp = new ResponseBase<Organization>();
		try {
			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				return resp;
			}

			Organization or = organizationService.findById(req.getId());
			resp.setResult(or);
			resp.setResultCode(StatusCode.SUCCESS.key());
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: getOrganizationList
	 * @Description: 分页获取系统模块
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	private ResponseBase<List<Organization>> list(
			@RequestBody OrganizationReq req) {
		ResponseBase<List<Organization>> resp = new ResponseBase<List<Organization>>();
		List<Organization> orList = new ArrayList<Organization>();
		try {

			if (req == null || req.getUserId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				return resp;
			}

			Long userId = req.getUserId();

			SysUser user = userService.findById(userId);
			if (user.getOrgId() != null) {
				Organization or = organizationService.findById(user.getOrgId());
				if (or != null) {
					orList = getSon(or);
				}
			}
			resp.setSize(orList.size());
			resp.setResult(orList);
			resp.setResultCode(StatusCode.SUCCESS.key());
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}

		return resp;
	}

	/**
	 * @Title: getOrganizationList
	 * @Description: 分页获取系统模块
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/listAll")
	public ResponseBase<List<Organization>> listAll() {


		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addSql(" where 1=1 and status = 1 ");

		return getResultByFilter(hqlFilter);
	}

	/**
	 * @Title: getOrganizationList
	 * @Description: 分页获取系统模块
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/listAllNormal")
	public ResponseBase<List<Organization>> listAllNormal() {


		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addSql(" where 1=1 and depType = 1 and status = 1 ");

		return getResultByFilter(hqlFilter);
	}

	/**
	 * @Title: getOrganizationList
	 * @Description: 分页获取组织架构部门
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/listAllDep")
	public ResponseBase<List<Organization>> listAllDep() {

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addSql(" where 1=1 and status = 1  and orgType != 4 ");
		return getResultByFilter(hqlFilter);
	}



	/**
	 * @Title: getOrganizationList
	 * @Description: 分页获取系统模块
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/listAllByUser", method = RequestMethod.POST)
	public ResponseBase<List<OrganizationRes>> listAllByUser(@RequestBody OrganizationReq req) {

		ResponseBase<List<OrganizationRes>> resp = new ResponseBase<List<OrganizationRes>>();

		if(req == null || req.getActUserId() == null ){
			resp.setMsg("请登录后重试，请重试");
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			return  resp;
		}

		Long userId = req.getActUserId();

		logger.info("user login and will get orgList userId={}", userId);

		List<Organization> orList = new ArrayList<Organization>();

		List<OrganizationRes> orResList = new ArrayList<OrganizationRes>();

		try {
			orList = organizationService.findByUser(userId);
			if(orList != null){
				//将组织架构信息导入
				for(Organization org : orList){
					OrganizationRes orgRes = new OrganizationRes();
					ReqToModelHelper.copyReqValueToModel(org, orgRes);
					orResList.add(orgRes);
				}
				resp.setSize(orList.size());
				resp.setResult(orResList);
				resp.setResultCode(StatusCode.SUCCESS.key());
			}else{
				resp.setSize(0);
				resp.setResult(null);
				resp.setResultCode(StatusCode.ERROR.key());
			}
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}

		return resp;
	}

	/**
	 * @Title: getOrganizationList
	 * @Description: 分页获取系统模块
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/updateName", method = RequestMethod.POST)
	public ResponseBase<List<OrganizationRes>> updateOrg(@RequestBody OrganizationReq req) {
		ResponseBase<List<OrganizationRes>> resp = new ResponseBase<List<OrganizationRes>>();

		if(req == null || req.getId() == null || StringHelper.isEmpty(req.getNewName()) ){
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			resp.setMsg("参数错误");
			return resp;
		}

		if(req.getActUserId() == null){
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			resp.setMsg("登录超时，请重新登录后再进行操作！");
			return resp;
		}

		Integer id = req.getId();
		String name = req.getNewName();

		Organization org = organizationService.findById(id);

		if(org == null ){
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			resp.setMsg("参数错误");
		}
		org.setName(name);


		String fullName = "";

		String[] idsStr = org.getCode().split("-");
		for (int i = 0; i < idsStr.length - 1 ; i++) {
			Integer parentId = Integer.valueOf(idsStr[i]);
			Organization parent = organizationService.findById(parentId);
			if (parent.getOrgType().equals(Constant.ORGANIZATION_TYPE_DEPARTMENT) || parent.getOrgType().equals(Constant.ORGANIZATION_TYPE_DUTIES)) {
				fullName = fullName + "-" + parent.getName();
			}
		}

		fullName = fullName + "—" + name;
		fullName = fullName.substring(1, fullName.length());

		org.setFullName(fullName);
		org.setFlag02(fullName);

		organizationService.update(org, req.getActUserId());

//		org = organizationService.findById(org.getId());
//		org.setFullName(organizationService.getDepNameById(org.getId()));
//		org.setFlag02(organizationService.getDepNameById(org.getId()));
//		organizationService.update(org, req.getActUserId());

		List<Organization> orResList =  orgNewService.getSubOrgList(org.getId());
		orgNewService.updateAllName(orResList, req.getActUserId());

		resp.setResultCode(StatusCode.SUCCESS.key());

		resp.setSize(orResList.size());
		resp.setMsg("成功");

		return resp;
	}


	/**
	 * @Title: saveOrganization
	 * @Description: TODO
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public ResponseBase<Organization> save(@RequestBody OrganizationReq req) {
		ResponseBase<Organization> resp = new ResponseBase<Organization>();

		try {

			if(req == null || StringHelper.isEmpty(req.getName())){
				resp.setMsg("参数错误,保存失败！");
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				return resp;
			}

			if(req.getActUserId() == null){
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("登录超时，请重新登录后再进行操作！");
				return resp;
			}


			logger.info("org save info req={}", req.toString());

			Organization model = new Organization();
			ReqToModelHelper.copyReqValueToModel(req, model);
			model.setDepType(req.getDepType());

			CheckInfo checkInfo = organizationService.check(model);

			logger.info("save org check msg = "+  checkInfo.toString());

			if(checkInfo.getResult() == false){
				resp.setMsg(checkInfo.getResultMsg());
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				return resp;

			}

			model.setCreator(req.getActUserId());

			Integer id = organizationService.add(model);

			resp.setResult(model);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("添加成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: updateOrganization
	 * @Description:
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public ResponseBase<Organization> update(@RequestBody OrganizationReq req) {
		ResponseBase<Organization> resp = new ResponseBase<Organization>();
		try {
			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				return resp;
			}

			if(req.getActUserId() == null){
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("登录超时，请重新登录后再进行操作！");
				return resp;
			}

			Organization model = organizationService.findById(req.getId());
			// 修改名称
			model.setName(req.getName());
			model.setUpdatedts(System.currentTimeMillis());
			// 修改标识符
			model.setFlag01(req.getFlag01());
			model.setFlag02(req.getFlag02());
			organizationService.update(model, req.getActUserId());


			//更改子标的组织架构
			Organization newOrg =organizationService.findById(req.getId());

			//更改标签02
			newOrg.setFlag02(getFullName(newOrg));
			organizationService.update(newOrg, req.getActUserId());

			//更改flag02
			List<Organization> orgList = getSon( newOrg);
			for(Organization org : orgList){
				org.setFlag02(getFullName(org));
				organizationService.update(org, req.getActUserId());
			}

			resp.setResult(model);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("修改成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}


	/**
	 * @Title: deleteOrganization
	 * @Description:
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public Response<Boolean> delete(@RequestBody OrganizationReq req) {
		Response<Boolean> resp = new Response<Boolean>();
		try {


			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				return resp;
			}

			if (req.getActUserId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("登录超时，请重新登录！");
				return resp;
			}

			Integer id = req.getId();
			Organization org = organizationService.findById(id);
			if(org == null){
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("该组织架构不存在！");
				return resp;
			}

			if(org.getStatus() == 0){
				resp.setResultCode(StatusCode.ERROR.key());
				resp.setMsg("该组织架构已冻结，不能再次冻结！");
				return resp;
			}


			CheckInfo check = organizationService.deleteCheck(id);
			if(check.getResult()){
				organizationService.delete(id, req.getActUserId());
				resp.setResult(true);
				resp.setResultCode(StatusCode.SUCCESS.key());
				resp.setMsg("删除成功");
			}else{
				resp.setResult(false);
				resp.setResultCode(StatusCode.ERROR.key());
				resp.setMsg(check.getResultMsg());
			}
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setResultCode(StatusCode.EXCEPTION.key());
			resp.setMsg("操作异常，请重试");
		}

		return resp;
	}

	@ResponseBody
	@RequestMapping(value = "/excel")
	public void excel(HttpServletRequest request,
			HttpServletResponse response) {

		List<Organization> orList = new ArrayList<Organization>();

		HqlFilter hqlFilter = new HqlFilter();

		orList = organizationService.findByFilter(hqlFilter);

		String head = "id, pid, 资源类型, code, 创建人, 名称, 创建时间, 更改时间, 状态, 是否是负责人, 标识符1, 标识符2";


		List<OrganizationExcelRes> orExcelList =  getExcelList(orList);

		ExcelHelper newExcel = new ExcelHelper(orExcelList, head);
		Workbook wb = newExcel.outputExcel();

		response.setContentType("application/vnd.ms-excel");

		String titlename = "组织架构表";
		try {
			response.setHeader("Content-disposition", "attachment; filename="
					+ new String((titlename).getBytes("gbk"), "iso8859-1")
					+ ".xlsx");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		OutputStream ouputStream;
		try {
			ouputStream = response.getOutputStream();
			wb.write(ouputStream);
			ouputStream.flush();
			ouputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}


	public List<Organization> getSon(Organization or) {

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addSql(" where code like '" + or.getCode() + "-%'");
		System.out.println(hqlFilter.getWhereHql());
		List<Organization> orgList = organizationService
				.findByFilter(hqlFilter);
		System.out.println("orgList size = " + orgList.size());
		orgList.remove(or);
		return orgList;
	}

	public String getFullName(Organization or) {
		String name = "";
		String code = or.getCode();
		String []parent = code.split("-");
		for(int i = 0; i < parent.length; i++ ){
			Integer parentId = Integer.valueOf(parent[i]);
			Organization parentOrg = organizationService.findById(parentId);
			if(parentOrg != null && (parentOrg.getOrgType() == Constant.ORGANIZATION_TYPE_DEPARTMENT
					||parentOrg.getOrgType() == Constant.ORGANIZATION_TYPE_DUTIES)){
					name = name + "-" +  parentOrg.getName();
				}

		}
		if(StringHelper.isNotEmpty(name)){
			name = name.substring(1, name.length());
		}
		return name ;
	}


	public Boolean isLeaf(Organization or) {
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addSql(" where code like '" + or.getCode() + "-%'");
		System.out.println(hqlFilter.getWhereHql());
		List<Organization> orgList = organizationService
				.findByFilter(hqlFilter);
		return orgList.size() == 0 ? true : false;
	}

	public Boolean existIn(List<Organization> orList, Long id) {
		boolean result = false;

		for (Organization orRes : orList) {
			if (orRes.getId().longValue() == id.longValue()) {
				result = true;
			}
		}

		return result;
	}

	public List<OrganizationExcelRes> getExcelList(List<Organization> orList){
		List<OrganizationExcelRes> orExcelList = new ArrayList<OrganizationExcelRes>();

		for(Organization org : orList){
			OrganizationExcelRes orgExcel = new OrganizationExcelRes();
			orgExcel.setCol010id(org.getId().toString());
			orgExcel.setCol020parentID(org.getParentID().toString() );

			if(org.getOrgType().equals(Constant.ORGANIZATION_TYPE_GROUP)){

				orgExcel.setCol030orgType("集团");
			}else if (org.getOrgType().equals(Constant.ORGANIZATION_TYPE_COMPANY)){

				orgExcel.setCol030orgType("公司");
			}else if (org.getOrgType().equals(Constant.ORGANIZATION_TYPE_DEPARTMENT)){

				orgExcel.setCol030orgType("部门");
			}else if (org.getOrgType().equals(Constant.ORGANIZATION_TYPE_DUTIES)){

				orgExcel.setCol030orgType("职务");
			}

			orgExcel.setCol040ocode(org.getCode());
			if( org.getCreator()!= null){
				SysUser user = userService.findById(org.getCreator());
				if(user != null){
				orgExcel.setCol050creator(user.getRealName());
				}
			}

			orgExcel.setCol060name(org.getName());

			if(org.getCts() != null){
				orgExcel.setCol070cts(new Timestamp(org.getCts()).toString());
			}

			if(org.getUpdatedts() != null){
				orgExcel.setCol080updatedts(new Timestamp(org.getUpdatedts()).toString());
			}

			if(org.getIsHeader() != null){
				orgExcel.setCol100isHeader(org.getIsHeader() == 1?"是":"否" );
			}
			 
			orgExcel.setCol110flag01(org.getFlag01());
			orgExcel.setCol120flag02( org.getFlag02());
			
			orExcelList.add(orgExcel);
		}
		
		return orExcelList;
		
	}

	private  ResponseBase<List<Organization>> getResultByFilter(HqlFilter hqlFilter){

		ResponseBase<List<Organization>> resp = new ResponseBase<>();
		try {
			List<Organization> orList = organizationService.findByFilter(hqlFilter);
			resp.setSize(orList.size());
			resp.setResult(orList);
			resp.setResultCode(StatusCode.SUCCESS.key());
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}


}
